package cn.jingyuan.swan.gw.web.filter.zuul;

import cn.jingyuan.swan.gw.service.AccessLogService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.Setter;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Zuul filter：记录日志
 */
public class ZuulLogRecordFilter extends ZuulFilter {

    @Setter
    AccessLogService accessLogService;

    public ZuulLogRecordFilter(AccessLogService accessLogService) {
        this.accessLogService = accessLogService;
    }

    /**
     * 是否执行该过滤器 ：false -->则不执行该 filter
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器类型
     * 顺序:：pre ->routing -> post，,以上 3 个顺序出现异常时都可以触发 error 类型的 filter
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    /**
     * 同 filterType 类型中，order 值越大，优先级越低
     */
    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER + 2;
    }

    @Override
    public Object run() {
        // 代理后响应日志处理
        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse response = ctx.getResponse();

        // 把路由的 serviceId 放入作用域
        request.setAttribute(FilterConstants.SERVICE_ID_KEY, ctx.get(FilterConstants.SERVICE_ID_KEY));

        accessLogService.sendLog(request, response, null);

        return null;
    }

}
